import { useEffect,useRef } from 'react'

const useInterval = (callback:()=>void,delay?:number | null)=>{
  const saveCallback = useRef<()=> void>(()=>{})

  useEffect(()=>{
    saveCallback.current = callback
  })

  useEffect(()=>{
    if(delay !== null){
      const interval = setInterval(()=>saveCallback.current(),delay|| 0)
      return ()=> clearInterval(interval)
    }

    return undefined
  },[delay])
}

export default useInterval